import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr'

// SignalR连接配置
export class SignalRService {
  private connection: HubConnection | null = null
  private isConnected = false

  // 创建连接
  async createConnection(): Promise<HubConnection> {
    if (this.connection && this.isConnected) {
      console.log('SignalR连接已存在，返回现有连接')
      return this.connection
    }

    console.log('创建新的SignalR连接...')
    
    this.connection = new HubConnectionBuilder()
      .withUrl('http://localhost:5121/hubs/enterout', {
        skipNegotiation: false, // 允许协商
        transport: 1 // WebSockets transport
      })
      .withAutomaticReconnect([0, 2000, 10000, 30000]) // 重连策略
      .configureLogging(LogLevel.Debug) // 改为Debug级别以获取更多信息
      .build()

    // 设置连接事件监听
    this.connection.onclose((error) => {
      console.log('SignalR连接已关闭:', error)
      this.isConnected = false
    })

    this.connection.onreconnecting((error) => {
      console.log('SignalR正在重连:', error)
      this.isConnected = false
    })

    this.connection.onreconnected((connectionId) => {
      console.log('SignalR重连成功:', connectionId)
      this.isConnected = true
      console.log('重连后连接状态:', this.isConnected)
    })

    try {
      console.log('尝试启动SignalR连接...')
      await this.connection.start()
      this.isConnected = true
      console.log('SignalR连接成功，连接ID:', this.connection.connectionId)
      return this.connection
    } catch (error) {
      console.error('SignalR连接失败:', error)
      this.isConnected = false
      throw error
    }
  }

  // 获取连接状态
  getConnectionStatus(): boolean {
    return this.isConnected
  }

  // 获取连接实例
  getConnection(): HubConnection | null {
    return this.connection
  }

  // 关闭连接
  async stopConnection(): Promise<void> {
    if (this.connection) {
      await this.connection.stop()
      this.connection = null
      this.isConnected = false
      console.log('SignalR连接已停止')
    }
  }

  // 监听出入库数据
  onReceiveEnterOutData(callback: (data: any[]) => void): void {
    if (this.connection) {
      console.log('设置监听器: ReciveenterOutDTOs')
      
      // 先移除之前的监听器，避免重复
      this.connection.off('ReciveenterOutDTOs')
      
      this.connection.on('ReciveenterOutDTOs', (data) => {
        console.log('收到出入库数据:', data)
        console.log('数据类型:', typeof data)
        console.log('是否为数组:', Array.isArray(data))
        console.log('数据内容:', JSON.stringify(data, null, 2))
        callback(data)
      })
      
      // 测试监听器是否设置成功
      console.log('监听器设置完成，当前连接状态:', this.isConnected)
    } else {
      console.error('SignalR连接未建立，无法设置监听器')
    }
  }

  // 移除监听器
  offReceiveEnterOutData(): void {
    if (this.connection) {
      this.connection.off('ReciveenterOutDTOs')
    }
  }
}

// 创建全局SignalR服务实例
export const signalRService = new SignalRService()

// 出入库数据类型定义
export interface EnterOutDTO {
  id: number
  stockId: number
  code: string
  dateTime: string
  businessType: number
  stId: number
  stName: string
  depotId: number
  depotName: string
  incomingQuantity: number
  incomingMoney: number
  state: number
}

// 分析数据类型
export interface AnalysisData {
  totalIn: number
  totalOut: number
  netChange: number
  dailyStats: {
    date: string
    inCount: number
    outCount: number
    netChange: number
  }[]
  topProducts: {
    productName: string
    totalQuantity: number
    type: '入库' | '出库'
  }[]
  warehouseStats: {
    warehouse: string
    inCount: number
    outCount: number
  }[]
}